package com.datounet.flutterapp.methodChannel;

import android.util.Log;

import androidx.annotation.Nullable;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;

/**
 * @author 41784
 */
public class MethodChannelPlugin implements MethodChannel.MethodCallHandler, FlutterPlugin {
    private static final String METHOD_CHANNEL_NAME = "MethodChannelPlugin";
    private static MethodChannel channel;
    private static OnMethodCallDelegate callDelegate;

    /**
     * Plugin registration.
     */
    public static void registerWith(PluginRegistry.Registrar registrar) {
        MethodChannelPlugin methodChannelPlugin = new MethodChannelPlugin();
        methodChannelPlugin.initChannel(registrar.messenger());
    }

    public MethodChannelPlugin() {
        callDelegate = new OnMethodCallDelegate();
    }

    /**
     * 用invoke方法调用dart
     */
    public static void invokeDartMethod(String methodName, @Nullable Object args, @Nullable MethodChannel.Result callback) {
        if (null == channel) {
            Log.e(METHOD_CHANNEL_NAME, "MethodChannel is null");
            return;
        }
        if (null == callback) {
            channel.invokeMethod(methodName, args);
        } else {
            channel.invokeMethod(methodName, args, callback);
        }

    }

    private void initChannel(BinaryMessenger messenger) {
        channel = new MethodChannel(messenger, METHOD_CHANNEL_NAME);
        channel.setMethodCallHandler(new MethodChannelPlugin());
    }

    private void releaseChannel() {
        channel.setMethodCallHandler(null);
        channel = null;
    }

    @Override
    public void onMethodCall(MethodCall call, MethodChannel.Result result) {
        Log.e(METHOD_CHANNEL_NAME, "onDartMethodCall: " + "methodName->" + call.method + "    -args->" + call.arguments);
        callDelegate.dispatch(call, result);
    }

    @Override
    public void onAttachedToEngine(FlutterPluginBinding binding) {
        Log.e("MethodChannelPlugin", "onAttachedToEngine");
        initChannel(binding.getBinaryMessenger());
    }

    @Override
    public void onDetachedFromEngine(FlutterPluginBinding binding) {
        releaseChannel();
    }
}